import {Component, Input, OnInit} from '@angular/core';
import {FileModel} from "../app.component";
import {NzModalService} from "ng-zorro-antd/modal";
import {invoke} from "@tauri-apps/api";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-file-list',
  templateUrl: './file-list.component.html',
  styleUrls: ['./file-list.component.css']
})
export class FileListComponent implements OnInit {

  isVisible = false;
  @Input()
  listOfData: FileModel[] = [];
  fileModel: FileModel | undefined = undefined;

  constructor(private modal: NzModalService, private message: NzMessageService) {
  }

  ngOnInit(): void {
  }

  showDetail(data: FileModel ) {
    this.isVisible = true;
    this.fileModel = data;
    console.log("showDetail: ", data);
  }

  del(data: FileModel) {
    this.modal.confirm({
      nzTitle: '确定要删除该文件对应的所有重复文件吗？此操作不可撤销',
      nzWidth: '60%',
      nzContent: `<b>${data.name}，重复文件数量: ${data.path.length}</b>`,
      nzOkText: '确认删除',
      nzOkType: 'primary',
      nzClosable: false,
      nzOkDanger: true,
      nzOnOk: () => {
        return invoke('delete_file_list', {filepath: data.path})
          // `invoke` 返回的是一个 Promise
          .then((response) => {
              console.log("delete_file_list: ", response);
              this.message.create("success", "删除成功");
              this.listOfData = this.listOfData.filter(i => i.md5 != data.md5);
            }
          ).catch((e) => {
            console.error("deleteFileError", e);
            this.message.create("error", e);
          });
      },
      nzCancelText: '我再想想',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  delFile(filePath: string) {
    if (this.fileModel) {
      this.modal.confirm({
        nzTitle: '确定要删除该文件吗，此操作不可撤销',
        nzWidth: '60%',
        nzContent: `<b>${filePath}</b>`,
        nzOkText: '确认删除',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzClosable:false,
        nzOnOk: () => {
          return invoke('delete_file', {filepath: filePath})
            // `invoke` 返回的是一个 Promise
            .then((response) => {
                console.log("delete_file: ", response);
                this.message.create("success", "删除成功");
                if (this.fileModel) {
                  this.fileModel.path = this.fileModel.path.filter(i => i != filePath);
                }
              }
            ).catch((e) => {
              console.error("deleteFileError", e);
              this.message.create("error", e);
            });
        },
        nzCancelText: '我再想想',
        nzOnCancel: () => console.log('Cancel')
      });
    }
  }
}


